import {Component} from 'react';
import {observer} from 'mobx-react';
import {action,observable,useStrict} from 'mobx';
import Pubsub from 'pubsub-js';
useStrict(true);
//基础库
export class BaseUtils {
	get DEBUG(){
		return process.env.NODE_ENV !== 'production'
	}
	API_URL='http://shop.dev.xpos.bringke.com/index.php/api/pos/'
	// API_URL='http://192.168.0.127/bringke/xpos-php/shop/index.php/api/pos/'
	GLOBAL_API_URL='http://shop.dev.xpos.bringke.com/index.php/api/global/'
	// GLOBAL_API_URL='http://192.168.0.127/bringke/xpos-php/shop/index.php/api/global/'	
    openWin(s_name, o_param){
		// if(!Actions[s_name]){
		// 	throw `页面 ${s_name} 未定义`;
		// }
		// Actions[s_name](o_param);
	}
    //关闭页面
	closeWin(s_name){
		// Actions.pop(s_name);
	}
	//关闭到页面，当前页面和s_name页面之前的页面全部从栈内移除
	popTo(s_name){
		// Actions.popTo(s_name);
	}
	//替换当前页
	replaceTo(s_name,o_param={}){
		// Actions[s_name]({type:ActionConst.REPLACE,...o_param});
	}
    //toast
	toast(s_msg,i_duration=3,f_callBack,s_type='warning',s_position='top',s_btnText=' '){
		// i_duration = i_duration*1000;
		// if(RootComponent.toast && RootComponent.toast._root){
		// 	RootComponent.toast._root.showToast({config:{text: s_msg,position: s_position,buttonText: s_btnText,duration:i_duration,type:s_type}});
		// }
		// if(f_callBack){
        //     setTimeout(f_callBack,i_duration);
        // }
	}
	//显示loading
	showProgress(b_show,s_label=''){
		// RootComponent.loading.setState({b_show,s_label})
	}
	//读取缓存数据
	// getLocalData(s_key,f_callBack){
	// 	const self = this;
	// 	storage.load({
	// 		key: s_key,
	// 	}).then(res => {
	// 		f_callBack(res);
	// 	}).catch(err => {
	// 		self.DEBUG && console.log(err);
	// 		f_callBack(null);
	// 	})
	// }
	// //缓存数据
	// setLocalData(s_key,data){
	// 	if(s_key === this.USER_DATA_KEY){
	// 		this.VERIFY_DATA = data;
	// 	}
	// 	storage.save({key: s_key,data: data});
	// }
	//处理请求参数
	_handlerParams(o_param={},s_method='GET',b_verify=false){
		let self = this;
		if(!o_param['act'] || ! o_param['op']){
			throw "未传入act或op";
		}
		if(b_verify){
			const verifyData = self.VERIFY_DATA || {};
			if(!verifyData.token || !verifyData.account ||!verifyData.store_sn ){
				// self.showProgress(false);
			}
			Object.assign(o_param,verifyData);
		}
		let s_requestUrl = this.API_URL + o_param['act'] +'/' + o_param['op'];
		if(o_param.b_global){
			s_requestUrl = this.GLOBAL_API_URL + o_param['act'] +'/' + o_param['op'];
			delete o_param['b_global'];
		}
		delete o_param['act'];
   	 	delete o_param['op'];
		let o_body = null;
		let s_url = '';
		for(let [key,value] of Object.entries(o_param)){
			s_url += key+'='+value+'&';
		}
		s_url = s_url.replace(/&$/,'');
		const b_get = s_method.toLocaleLowerCase() === 'get';
		if(b_get){
			if(s_url){
			 	s_requestUrl += '?'+s_url;
			}
		}else{
			o_body = s_url;
		}
		const o_fetchData = {
		  	method: s_method,
		  	headers: {
		    	'Accept': 'application/json',
		    	'Content-Type': b_get?'application/json':'application/x-www-form-urlencoded',
		  	},
			timeout:10000,
		  	body: o_body
		}
		return {s_requestUrl,o_fetchData};
	}
	_requset(o_param={},f_succBack=null,b_showProgress=true,s_method='GET',b_verify=false,f_errorCallBack=null){
		let self = this;
		const {s_requestUrl,o_fetchData} = this._handlerParams(o_param,s_method,b_verify);
		b_showProgress && self.showProgress(true);
		fetch(s_requestUrl,o_fetchData).then((response) => {self.DEBUG && console.log(response);return response.json()}).then((res) => {
			self.DEBUG && console.log(res);
			let {code} = res;
			if(code === 0){
				f_succBack && action(f_succBack)(res);
			}else if(code === -10){
				self.openWin('user_login');
			}else if(code === -20){
				f_succBack && action(f_succBack)(res);
			}else{
				self.toast(res.msg);
			}
			self.showProgress(false);
      	}).catch((error) => {
			self.DEBUG && console.log(error);
			self.toast('网络连接异常，请重新尝试');
			self.showProgress(false);
			f_errorCallBack && f_errorCallBack(error);
      	});
	}
	getNormal(o_param,f_succBack=null,b_showProgress=true){
		this._requset(o_param,f_succBack,b_showProgress,"GET");
	}
	postNormal(o_param,f_succBack=null,b_showProgress=true){
		this._requset(o_param,f_succBack,b_showProgress,"POST");
	}
	getVerify(o_param,f_succBack=null,b_showProgress=true){
		this._requset(o_param,f_succBack,b_showProgress,"GET",true);
	}
	postVerify(o_param,f_succBack=null,b_showProgress=true){
		this._requset(o_param,f_succBack,b_showProgress,"POST",true);
	}
	//多个异步操作处理
    // promiseAll(f_succBack,...promiseParams){
	// 	let self = this;
	// 	self.showProgress(true);
	// 	let promiseList = promiseParams.map((item)=>{
	// 		let [o_param,s_method='GET',b_verify=true] = item;
	// 		const {s_requestUrl,o_fetchData} = self._handlerParams(o_param,s_method,b_verify);
	// 		return fetch(s_requestUrl,o_fetchData);
	// 	});
	// 	const catchFuc = (error) => {
	// 		self.DEBUG && console.log(error);
	// 		self.toast('网络连接异常，请重新尝试');
	// 		self.showProgress(false);
    //   	};
	// 	Promise.all([...promiseList]).then((responses) => {
	// 		const responseList = responses.map((response)=>{
	// 			return response.json();
	// 		});
	// 		Promise.all(responseList).then((responseJsons)=>{
	// 			let b_needLogin = false;
	// 			let s_errorCode = '';
	// 			let dataList = [];
	// 			responseJsons.map((res)=>{
	// 				const {data,code,msg} = res;
	// 				if(code === 0){
	// 					dataList.push(data);
	// 				}else if(code === -10){
	// 					b_needLogin = true;
	// 				}else{
	// 					s_errorCode = msg;
	// 				}
	// 			});
	// 			if(b_needLogin){
	// 				self.openWin('user_login');
	// 			}else if(s_errorCode){
	// 				self.toast(s_errorCode);
	// 			}else{
	// 				self.DEBUG && console.log(dataList);
	// 				f_succBack && action(f_succBack)(dataList);
	// 			}
	// 			self.showProgress(false);
	// 		}).catch(catchFuc);
    //   	}).catch(catchFuc);
    // }
	//全局事件处理：监听事件
    addEvt(s_evtName,f_listener){
    	Pubsub.subscribe(s_evtName,action(f_listener));
    }
    //全局事件处理：移除事件
    removeEvt(s_evtName){
    	//移除所有该类型事件监听
    	Pubsub.unsubscribe(s_evtName);
    }
    //全局事件处理：派发事件
    sendEvt(s_evtName,o_data){
		Pubsub.publish(s_evtName,o_data);
    }
	//校验手机号
    checkMobile(i_mobileNum){
        let re = new RegExp(/^1(3|4|5|7|8)\d{9}$/);
        return re.test(i_mobileNum);
    }
    //格式化数字，比如：0->0.00
    getNumFormat(n_num,i_len=2){
        n_num = parseFloat(n_num) || 0;
        return n_num.toFixed(i_len);
    }
    //格式化时间日期,time:秒数,type:0,输出年月日,1.输出时分秒,2.全部输出
    getTimeFormat(s_time,i_type=0){
        s_time = s_time ? new Date(parseInt(s_time)*1000) : new Date();
        let a_YMDList = [s_time.getFullYear(),s_time.getMonth()+1,s_time.getDate()];
        let a_HMSList = [s_time.getHours(),s_time.getMinutes(),s_time.getSeconds()];
        a_YMDList.map(function(value,index){
            a_YMDList[index] = value.toString().replace(/(^\d{1}$)/,"0"+"$1");
        });
        a_HMSList.map(function(value,index){
            a_HMSList[index] = value.toString().replace(/(^\d{1}$)/,"0"+"$1");
        });
        if(i_type === 0){
            return a_YMDList.join('-');
        }else if(i_type === 1){
            return a_HMSList.join(':');
        }
        return `${a_YMDList.join('-')} ${a_HMSList.join(':')}`;
    }
    //截取字符串长度,超出部分显示...，一个中文算两个字符
    getSpliceStr(s_str,i_len){
        s_str = s_str || "";
        if(i_len >= s_str.replace(/[^\x00-\xff]/g, 'xx').length){
            return s_str;
        }
        let s_newStr='',i_newLen = 0,i_index = 0,i_charCode = 0;
        while (i_newLen<i_len){
            s_newStr += s_str[i_index];
            i_charCode = s_str.charCodeAt(i_index);
            i_newLen += (i_charCode >= 0 && i_charCode <= 128)? 1 : 2;
            i_index++;
        }
        return `${s_newStr}...`;
	}
	//将数组切割成多维数组
	arrToTwoDimension(a_list,s_twoLen){
        let num = Math.ceil(a_list.length/s_twoLen);
        let newList = [];
        let startIndex = 0;
        for (let i = 0; i < num; i++){
            newList[i]=a_list.slice(startIndex,startIndex+s_twoLen);
            startIndex += s_twoLen;
        }
        return newList;
    }
}
export const Base = new BaseUtils();

//store基类
const _map_key = 'com.basestore.map_key';
export class BaseStore extends Object{
    constructor(){
		super();
		this[_map_key] = observable.map(this);
		this.set = (obj)=>{
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					this[_map_key].set(key,obj[key]);
				}
			}
			return this;
		}
		this.get = (key)=>{
			return this[_map_key].get(key);
		}
		this.creatData = (obj)=>{
			return this.set({'basestore_creat_data':obj}).get('basestore_creat_data');
		}
	}
}
//全局事件
export let Global = observable.map({});
//基础组件，内置store
const _componet_store = 'com.basecomponet.componet_store';
@observer
export class BaseComponent extends Component {
	constructor(props){
		super(props);
		this[_componet_store] = new BaseStore().set({'componet_store_key':{}});
	}
	set store(value){
		this[_componet_store].set({'componet_store_key':value});
	}
	get store(){
		// console.log(object);
		return this[_componet_store].get('componet_store_key');
	}
}


